package org.noworks.game.engine;

import java.util.ArrayList;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.state.StateBasedGame;

public class Entity {
	private ArrayList<Component> components; // ArrayList of components in the
												// Entity

	private String id; // Unique ID of the Entity

	private Vector2f position; // Position of the entity
	private RenderComponent renderComponent; // RenderComponent of the Entity
	private float rotation; // Rotation of the Entity

	private float scale; // Scale of the Entity

	/**
	 * @param id
	 *            ID of the Entity
	 */
	public Entity(String id) {
		this.id = id;

		components = new ArrayList<Component>();

		position = new Vector2f(0, 0);
		scale = 1;
		rotation = 0;
	}

	/**
	 * Adds new component to the Entity. If the component is a RenderComponent
	 * it will place it as such and remove the old RenderComponent if there is
	 * one.
	 * 
	 * @param component
	 *            Component to add to the Entity
	 */
	public void addComponent(Component component) {
		if (RenderComponent.class.isInstance(component)) {
			if (renderComponent != null)
				components.remove(renderComponent);
			renderComponent = (RenderComponent) component;
		}
		component.setOwner(this);
		components.add(component);
	}

	public Component getComponent(String id) {
		for (Component c : components) {
			if (c.getId().equalsIgnoreCase(id))
				return c;
		}
		return null;
	}

	public int getHeight() {
		if (renderComponent == null)
			return -1;
		return renderComponent.getHeight();
	}

	public String getId() {
		return id;
	}

	public Vector2f getPosition() {
		return position;
	}

	public float getRotation() {
		return rotation;
	}

	public float getScale() {
		return scale;
	}

	public int getWidth() {
		if (renderComponent == null)
			return -1;
		return renderComponent.getWidth();
	}

	public void render(GameContainer gc, StateBasedGame sbg, Graphics g) {
		if (renderComponent != null)
			renderComponent.render(gc, sbg, g);
	}

	public void setPosition(Vector2f position) {
		this.position = position;
	}

	public void setRotation(float rotation) {
		this.rotation = rotation;
	}

	public void setScale(float scale) {
		this.scale = scale;
	}

	public void update(GameContainer gc, StateBasedGame sbg, int delta) {
		for (Component c : components)
			c.update(gc, sbg, delta);
	}

}
